/**
 *
 * @param schema
 * @param options
 * mongoose middleware example
 *
 */

module.exports = function (schema, options) {

    schema.virtual('loadedAt')
        .get(function () {
            return this._loadedAt;
        })
        .set(function (v) {
            return this._loadedAt = v;
        })

    schema.post(['find', 'findOne'], function (docs) {
        if (!Array.isArray(docs)) {
            docs = [docs]
        }
        const now = new Date()
        for (let doc of docs) {
            doc.loadedAt = now
        }

    })
}

// schema middleware
// const loadedAtPlugin = require('./loadedAt');
// const gameSchema = new Schema({ ... });
// gameSchema.plugin(loadedAtPlugin);


//global middleware

// const mongoose = require('mongoose');
// mongoose.plugin(require('./loadedAt'));
// const gameSchema = new Schema({ ... });
// const playerSchema = new Schema({ ... });
// // `loadedAtPlugin` gets attached to both schemas
// const Game = mongoose.model('Game', gameSchema);
// const Player = mongoose.model('Player', playerSchema);

// Officially Supported Plugins

// mongoose-autopopulate  Always populate() certain fields in your Mongoose schemas

// mongoose-lean-virtuals: Attach virtuals to the results of Mongoose queries when using .lean().